package server;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author: wudong
 * @create: 2021-07-27 11:20
 **/
public class WebAppClassLoader extends ClassLoader{
    private String loadrootpath;

    public WebAppClassLoader(String loadrootpath) {
        super();
        this.loadrootpath = loadrootpath;
        if(!loadrootpath.endsWith("/")){
            this.loadrootpath = loadrootpath + "/";
        }
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] classbytes = null;
            classbytes = loadclassbytes(name);
            //定义类向JVM输入字节码文件
            Class<?> aClass = defineClass(name, classbytes, 0,
                    classbytes.length);
            return aClass;
        } catch (IOException e) {
            throw new ClassNotFoundException(name);
        }
    }
    private byte[] loadclassbytes(String name) throws IOException {
        String contextpath = loadrootpath;
        name = contextpath + name;
        String cname = name.replace(".", "/") + ".class";//获取字节码文件名
        byte[] bytes = Files.readAllBytes(Paths.get(cname));
        return bytes;
    }
}
